import { createFlatRequest } from '@sa/axios';
import { getServiceBaseURL } from '@/utils/service';
import { getAuthorization, handleExpiredRequest, showErrorMsg } from '../../request/shared';
import type { RequestInstanceState } from '../../request/type';

// 客户端专用请求实例，使用9500端口
const isHttpProxy = import.meta.env.DEV && import.meta.env.VITE_HTTP_PROXY === 'Y';
const { baseURL } = getServiceBaseURL(import.meta.env, isHttpProxy);

// 创建客户端请求实例，配置独立的baseURL
export const clientRequest = createFlatRequest<App.Service.Response, RequestInstanceState>(
  {
    // 客户端API使用9500端口，与管理端区分开
    baseURL: baseURL.replace('9530', '9500')
  },
  {
    async onRequest(config) {
      if (!config.noNeedToken) {
        const Authorization = getAuthorization();
        Object.assign(config.headers, { Authorization });
      }
      return config;
    },
    isBackendSuccess(response) {
      return String(response.data.code) === import.meta.env.VITE_SERVICE_SUCCESS_CODE;
    },
    async onBackendFail(response, instance) {
      // 复用token过期处理逻辑
      const expiredTokenCodes = import.meta.env.VITE_SERVICE_EXPIRED_TOKEN_CODES?.split(',') || [];
      if (expiredTokenCodes.includes(String(response.data.code))) {
        const success = await handleExpiredRequest(clientRequest.state);
        if (success) {
          const Authorization = getAuthorization();
          Object.assign(response.config.headers, { Authorization });
          return instance.request(response.config);
        }
      }
      return null;
    },
    transformBackendResponse(response) {
      return response.data.data;
    },
    onError(error) {
      let message = error.message;
      if (error.code === 'BACKEND_ERROR') {
        message = error.response?.data?.msg || message;
      }
      showErrorMsg(clientRequest.state, message);
    }
  }
);

/**
 * 客户端用户登录接口
 * 
 * @param sysUserLoginParam 登录参数对象，包含用户名和密码
 */
export function fetchClientLogin(sysUserLoginParam: {
  username: string;
  password: string;
}) {
  return clientRequest<Api.Auth.LoginToken>({
    url: '/api/user/userInfo/login',
    method: 'post',
    data: sysUserLoginParam
  });
}

/**
 * 获取客户端用户信息
 */
export function fetchClientUserInfo() {
  return clientRequest<Api.Auth.UserInfo>({
    url: '/api/user/userInfo/info',
    method: 'get'
  });
}

/**
 * 客户端用户退出登录
 */
export function fetchClientLogout() {
  return clientRequest({
    url: '/api/user/userInfo/logout',
    method: 'post'
  });
}

